package com.xzq.register;

import com.alibaba.nacos.api.exception.NacosException;
import com.alibaba.nacos.api.naming.NamingService;
import com.alibaba.nacos.api.naming.pojo.Instance;
import com.xzq.pojo.ProviderService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;

/**
 * @Author xzq
 * @Description //TODO
 * @Date 2021/12/2 17:29
 * @Version 1.0.0
 **/
public class NacosRegister implements Register{

    private Logger logger = LoggerFactory.getLogger(NacosRegister.class);
    private NamingService namingService;

    public NacosRegister(NamingService namingService) {
        this.namingService = namingService;
    }

    @Override
    public void register(ProviderService providerService) {
        try {
            namingService.registerInstance(providerService.getServiceName(), providerService.getHost(), providerService.getPort());
            logger.error("服务注册成功...{}", providerService);
        } catch (NacosException e) {
            e.printStackTrace();
            logger.error("服务注册失败...{}", providerService);
        }
    }

    @Override
    public ProviderService findService(String serviceName) {
        try {
            ProviderService providerService = new ProviderService();
            List<Instance> instances = namingService.getAllInstances(serviceName);
            Instance instance = instances.get(0);
            providerService.setServiceName(serviceName);
            providerService.setHost(instance.getIp());
            providerService.setPort(instance.getPort());
            return providerService;
        } catch (NacosException e) {
            e.printStackTrace();
        }
        return null;
    }
}
